package com.ruoyi.purchase.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.purchase.domain.PurchasePlan;
import com.ruoyi.purchase.service.IPurchasePlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 采购计划Controller
 *
 * @author kevinness
 * @date 2024-12-29
 */
@RestController
@RequestMapping("/purchasePlan")
public class PurchasePlanController extends BaseController
{
    @Autowired
    private IPurchasePlanService purchasePlanService;

    /**
     * 计划确认
     */
    @PostMapping("/confirm")
    public AjaxResult confirmPurchasePlan(@RequestBody List<PurchasePlan> purchasePlans){
        int result = 1;
        for (PurchasePlan purchasePlan : purchasePlans) {
            result = purchasePlanService.updatePurchasePlan(purchasePlan);
            if (result == 0) {
                break;
            }
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询采购计划列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PurchasePlan purchasePlan)
    {
        startPage();
        List<PurchasePlan> list = purchasePlanService.selectPurchasePlanList(purchasePlan);
        return getDataTable(list);
    }

    /**
     * 查询最新生成采购计划
     * 这里假设采购计划一个月生成一次
     */
    @GetMapping("/latest/list")
    public TableDataInfo latestList(PurchasePlan purchasePlan){
        startPage();
        List<PurchasePlan> list = purchasePlanService.selectLatestPurchasePlan(purchasePlan);
        return getDataTable(list);
    }

    /**
     * 查询最新的采购计划编号，用于插入新的采购计划
     */
    @GetMapping("/final/planNo")
    public AjaxResult getFinalPlanNo(PurchasePlan purchasePlan){
        return AjaxResult.success("操作成功",purchasePlanService.selectFinalPurchasePlan().getPlanNo());
    }

    /**
     * 假设采购计划一个月生成一次
     * 判断当月采购计划是否生成
     */
    @GetMapping("/check/isForecast")
    public AjaxResult checkIsForecast(){
        List<PurchasePlan> list = purchasePlanService.selectLatestPurchasePlan(new PurchasePlan());
        return AjaxResult.success(list.size());
    }

    /**
     * 导出采购计划列表
     */
    @Log(title = "采购计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PurchasePlan purchasePlan)
    {
        List<PurchasePlan> list = purchasePlanService.selectPurchasePlanList(purchasePlan);
        ExcelUtil<PurchasePlan> util = new ExcelUtil<PurchasePlan>(PurchasePlan.class);
        util.exportExcel(response, list, "采购计划数据");
    }

    /**
     * 获取采购计划详细信息
     */
    @GetMapping(value = "/{planNo}")
    public AjaxResult getInfo(@PathVariable("planNo") String planNo)
    {
        return success(purchasePlanService.selectPurchasePlanByPlanNo(planNo));
    }

    /**
     * 查询所有的采购计划并格式化返回前端
     */
    @PostMapping("/getStatistics")
    public AjaxResult getStatistics(@RequestBody String cycleNo){
        return success(purchasePlanService.getStatisticsInfo(cycleNo));
    }

    /**
     * 根据计划编号列表获取计划列表
     */
    @PostMapping("/getList")
    public AjaxResult getListInfo(@RequestBody List<String> planNoList){
        List<PurchasePlan> list = new ArrayList<PurchasePlan>();
        for(String planNo:planNoList){
            list.add(purchasePlanService.selectPurchasePlanByPlanNo(planNo));
        }
        return success(list);
    }

    /**
     * 新增采购计划
     */
    @Log(title = "采购计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PurchasePlan purchasePlan)
    {
        List<PurchasePlan> purchasePlans =
                purchasePlanService.selectLatestPurchasePlan(
                        new PurchasePlan(purchasePlan.getRawProductName()));
        for (PurchasePlan purchasePlan1 : purchasePlans) {
            if(purchasePlan1.getRawProductName().equals(purchasePlan.getRawProductName())){
                return error("当前货品的购买计划已存在，请直接修改！");
            }
        }
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        String username = SecurityUtils.getUsername();
        purchasePlan.setModifiedDate(formattedNow);
        purchasePlan.setModifiedBy(username);
        return toAjax(purchasePlanService.insertPurchasePlan(purchasePlan));
    }

    /**
     * 修改采购计划
     */
    @Log(title = "采购计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PurchasePlan purchasePlan)
    {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        String username = SecurityUtils.getUsername();
        purchasePlan.setModifiedDate(formattedNow);
        purchasePlan.setModifiedBy(username);
        return toAjax(purchasePlanService.updatePurchasePlan(purchasePlan));
    }

    /**
     * 删除采购计划
     */
    @Log(title = "采购计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{planNos}")
    public AjaxResult remove(@PathVariable String[] planNos)
    {
        for(String planNo:planNos){
            PurchasePlan purchasePlan =
                    purchasePlanService.selectPurchasePlanByPlanNo(planNo);
            if(purchasePlan.getPlanStatus().equals("已执行")){
                return error("已执行计划无法删除！");
            }
        }
        return toAjax(purchasePlanService.deletePurchasePlanByPlanNos(planNos));
    }

    /**
     * 需求预测
     */
    @PostMapping("/demand/forecast")
    public AjaxResult demandForcast(@RequestBody String cycleNo){
        return toAjax(purchasePlanService.demandForcast(cycleNo));
    }
}